package com.zhiyou100.www.bbs.login;

import com.zhiyou100.www.bbs.dao.TableUserDao;
import com.zhiyou100.www.bbs.entityclass.TableUser;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @packageName: ${NAME}
 * @className: ${PACKAGE_NAME}
 * @Description: TODO 判断是否登陆
 * @author: yang
 * @date: 2020/6/5
 */
@WebServlet(name = "JudgeLanding", urlPatterns = "/JudgeLanding")
public class JudgeLanding extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 设定编码集
        response.setContentType("text/html;charset=UTF-8");
        // 设定类型

        ServletContext servletContext = request.getServletContext();
        // 获取 Application域对象
        Object user = servletContext.getAttribute("user");
        // 获取 user

        if (user == null) {
            //  如果为null，则未登陆
            response.sendRedirect("http://localhost:8772/bbs/html/loginFailure.html");
        } else {
            // 登陆成功，判断用户名和密码是否正确
            TableUser user1 = (TableUser) user;
            // 转为 TableUser 类
            boolean login = new TableUserDao().login(user1.getUserName(), user1.getUserPwd());
            // 判断是否用户名和密码是否正确
            if (login){
                // 登陆 成功
                response.sendRedirect("http://localhost:8772/bbs/jsp/homepage.jsp");
                // 重定向
            }else {
                // 失败重新登陆
                response.sendRedirect("http://localhost:8772/bbs/html/loginFailure.html");
            }

        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
